import React, { FC, useRef, useState } from 'react'
import { ModalForm, ProFormInstance } from '@ant-design/pro-form'
import { Button, message, Tree } from 'antd'
import { useMount } from 'ahooks'
import { SetRoleDTO } from '@/model/auth/SetRoleDTO'
import { listByRoleId, updateModuleByRole } from '@/api/auth/menu'
import { MenuTreeDTO } from '@/model/auth/MenuTreeDTO'
import { SetMenuDTO } from '@/model/auth/SetMenuDTO'

interface SetMenuParam {
  roleId: number
}

const RolesSetMenuForm: FC<SetMenuParam> = (props) => {
  const { roleId } = props
  const formRef = useRef<ProFormInstance>()
  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 14 },
  }
  const [menus, setMenus] = useState([])
  const [selectedKeys, setSelectedKeys] = useState([])

  useMount(async () => {
    const menusResp:Array<MenuTreeDTO> = await listByRoleId(roleId)
    const selectedKeyTemp = []
    const treeMenuTransForm = (menu: MenuTreeDTO) => {
      if (menu.check) selectedKeyTemp.push(menu.id)
      const menuTree = {
        title: menu.name,
        key: menu.id,
        children: menu?.children?.map((item) => {
          return treeMenuTransForm(item)
        }),
      }
      return menuTree
    }
    setMenus(menusResp?.map((item) => {
      return treeMenuTransForm(item)
    }))
    setSelectedKeys(selectedKeyTemp)
  })

  const onCheck = (checkedKeys) => {
    setSelectedKeys(checkedKeys.checked)
  }

  return (
    <div className="role-set-menu-form">
      <ModalForm<SetRoleDTO>
        formRef={formRef}
        title="设置菜单"
        layout="horizontal"
        trigger={
          <Button type="link">
            设置菜单
          </Button>
        }
        {...formItemLayout}
        onFinish={async () => {
          const setMenuDTO = new SetMenuDTO()
          setMenuDTO.roleId = roleId
          setMenuDTO.modules = selectedKeys
          await updateModuleByRole(setMenuDTO)
          message.success('设置成功')
          return true
        }}
      >
        <Tree
          checkStrictly
          checkable
          onCheck={onCheck}
          defaultCheckedKeys={selectedKeys}
          treeData={menus}
        />
      </ModalForm>
    </div>
  )
}

export default RolesSetMenuForm
